<template>
  <div style="width:90%;">
    <!-- <div style="display: flex;align-items: center;justify-content: flex-end;padding-top: 100px;"><el-button @click="goback()" size="mini" type="primary">返回</el-button></div> -->

    <el-form
      :model="couponForm"
      :rules="rules"
      ref="couponForm"
      label-width="150px"
      :disabled="disabledFlag"
    >
      <el-input v-model="couponForm.uuid" type="hidden"></el-input>
      <el-input
        v-model="couponForm.couponType"
        type="hidden"
        value="3"
      ></el-input>
      <el-form-item label="优惠券编号：" prop="couponSeq">
        <el-input
          v-model="couponForm.couponSeq"
          :disabled="true"
          style="width:360px;"
          placeholder="保存后自动生成编号"
        ></el-input>
      </el-form-item>
      <el-form-item label="优惠券名称：" prop="couponName">
        <el-input
          v-model="couponForm.couponName"
          :disabled="disabledFlag"
          style="width:360px;"
          placeholder="请输入优惠券名称"
          maxlength="30"
          show-word-limit
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="活动日期：" prop="dateRanged">
        <el-date-picker
          v-model="couponForm.dateRanged"
          :disabled="disabledFlag"
          type="daterange"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item> -->
      <el-form-item label="使用说明：" prop="comments">
        <el-input
          type="textarea"
          v-model="couponForm.comments"
          :disabled="disabledFlag"
          placeholder="请输入卡券使用说明"
          maxlength="100"
          show-word-limit
          :autosize="{ minRows: 2 }"
          style="width:650px;"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="背景图片：" prop="couponPicture">
        <el-radio-group v-model="couponForm.couponPicture" :disabled="disabledFlag">
          <el-radio-button label="3"><img src="../../assets/images/coupon/couponBg3.png" style="width:80px;padding:0px;" /></el-radio-button>
          <el-radio-button label="2"><img src="../../assets/images/coupon/couponBg2.png" style="width:80px;" /></el-radio-button>
          <el-radio-button label="1"><img src="../../assets/images/coupon/couponBg1.png" style="width:80px;" /></el-radio-button>
        </el-radio-group>
      </el-form-item> -->

      <el-form-item label="卡券主图:" prop="mainPicList">
        <image-upload
          v-model="couponForm.mainPicList"
          :size="'400x400'"
          :limit="1"
        ></image-upload>
        <p class="tips" style="margin-left: 10px;color:red;">
          图片将用于消费者端卡券主图
        </p>
      </el-form-item>

      <el-form-item label="卡券详情图:" prop="detailPicList">
        <image-upload
          v-model="couponForm.detailPicList"
          :size="'400x400'"
          :limit="1"
        ></image-upload>
        <p class="tips" style="margin-left: 10px;color:red;">
          图片将用于消费者端卡券详情展示
        </p>
      </el-form-item>

      <!-- <el-form-item label="卡券优惠类型：" prop="discountType">
        <el-radio-group v-model="couponForm.discountType" :disabled="disabledFlag">
          <el-radio-button label="0">满减</el-radio-button>
          <el-radio-button label="1">折扣</el-radio-button>
        </el-radio-group>
      </el-form-item> -->
      <!-- <el-form-item label="卡券使用条件：" prop="conponLimitMoney" v-if="couponForm.discountType == '0'">
        <el-input
          v-model="couponForm.conponLimitMoney"
          :disabled="disabledFlag"
          style="width:360px;"
          @blur="moneyBlur($event, '卡券使用条件')"
          placeholder="请输入使用卡券的最低金额"
        ></el-input>
      </el-form-item> -->
      <el-form-item
        label="卡券面值："
        prop="couponMoney"
        v-if="couponForm.discountType == '0'"
      >
        <el-input
          v-model="couponForm.couponMoney"
          :disabled="disabledFlag"
          style="width:360px;"
          @blur="moneyBlur($event, '卡券面值')"
          placeholder="请输入卡券的面值"
        ></el-input>
      </el-form-item>
      <!--
      -->
      <el-form-item
        label="卡券折扣："
        prop="couponDiscount"
        v-if="couponForm.discountType == '1'"
      >
        <el-input
          v-model="couponForm.couponDiscount"
          :disabled="disabledFlag"
          style="width:360px;"
          @blur="discountBlur($event, '卡券折扣')"
          placeholder="请输入0-1以内的两位小数"
        ></el-input>
      </el-form-item>
      <el-form-item label="有效期类型：" prop="validType">
        <el-radio-group v-model="couponForm.validType" :disabled="disabledFlag">
          <el-radio-button label="2">有效日期</el-radio-button>
          <el-radio-button label="1">有效天数</el-radio-button>
          <el-radio-button label="3">指定日期</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="指定日期："
        prop="validDate"
        v-if="couponForm.validType == '3'"
      >
        <el-date-picker
          type="dates"
          value-format="yyyy-MM-dd"
          :disabled="disabledFlag"
          v-model="couponForm.validTimesList"
          placeholder="选择一个或多个日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item
        label="有效天数："
        prop="validDate"
        v-if="couponForm.validType == '1'"
      >
        <el-input
          v-model="couponForm.validDate"
          :disabled="disabledFlag"
          style="width:360px;"
          @blur="numberBlur($event, '有效天数')"
          placeholder="请输入有效天数"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="有效日期："
        prop="validCreateDate"
        v-if="couponForm.validType == '2'"
      >
        <el-date-picker
          v-model="couponForm.validDateRange"
          :disabled="disabledFlag"
          type="daterange"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="生效日期"
          end-placeholder="失效日期"
        ></el-date-picker>
      </el-form-item>
      <!--      <el-form-item label="单人限领张数：" prop="limitNum">-->
      <!--        <el-input-->
      <!--          v-model="couponForm.limitNum"-->
      <!--          :disabled="disabledFlag"-->
      <!--          style="width:360px;"-->
      <!--          @blur="numberBlur($event,'单人限领张数')"-->
      <!--          placeholder="请输入单人限领张数"-->
      <!--        ></el-input>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="目标会员：" prop="memberDTOS">-->
      <!--        <el-checkbox v-for="(item,index) in this.memberLevelList"-->
      <!--                     :key="index" @change="changebox(item)"-->
      <!--                     :checked="item.isChecked" :disabled="disabledFlag" -->
      <!--                     :label="item.memberLevelName">-->
      <!--        </el-checkbox>-->
      <!--      </el-form-item>-->
      <el-form-item label="是否启用：">
        <el-radio-group v-model="couponForm.status" :disabled="disabledFlag">
          <el-radio-button label="1">是</el-radio-button>
          <el-radio-button label="0">否</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="商品范围：">
        <el-radio-group v-model="couponForm.useScope" :disabled="disabledFlag">
          <el-radio-button label="0">通用</el-radio-button>
          <el-radio-button label="1">指定商品</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="适用商品："
        prop="useScopeList"
        v-if="couponForm.useScope == '1'"
      >
        <el-table
          :data="useScopeList"
          @selection-change="couponGoodsChecked"
          border
          v-if="couponForm.useScope == '1'"
          style="font-size: 10px;width:100%;"
          type="expand"
          height="300"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="goodsName"
            label="商品名称"
            width="200"
            header-align="center"
          ></el-table-column>
          <el-table-column
            prop="goodsSeq"
            label="商品编码"
            width="180"
            header-align="center"
          ></el-table-column>
          <el-table-column
            prop="goodsTypeName"
            label="商品分类"
            width="180"
            header-align="center"
          ></el-table-column>
          <el-table-column
            prop="salePrice"
            label="商品价格"
            header-align="center"
            align="right"
          ></el-table-column>
          <el-table-column
            prop="unitName"
            label="销售单位"
            header-align="center"
          ></el-table-column>
          <!-- <el-table-column prop="ifRangeDay" label="是否指定日期" width="550" align="center">
            <template slot-scope="scope">
              <div class="choose-date">
                <el-radio-group :disabled="disabledFlag" v-model="scope.row.ifRangeDay">
                  <el-radio-button :label="0">不限定</el-radio-button>
                  <el-radio-button :label="1">限定</el-radio-button>
                </el-radio-group>

                <div v-if="scope.row.ifRangeDay == 1" style="margin-left: 10px">
                  <el-date-picker
                    :disabled="disabledFlag"
                    v-model="scope.row.goodsRangeTimes_copy"
                    type="daterange"
                    align="right"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    :clearable="false"
                  ></el-date-picker>
                </div>
              </div>
            </template>
          </el-table-column> -->
        </el-table>

        <div style="margin-top:10px;">
          <el-button type="primary" @click="selectGoods()" v-if="!disabledFlag"
            >选择商品</el-button
          >
          <el-button @click="deleteGoods('couponForm')" v-if="!disabledFlag"
            >删除商品</el-button
          >
        </div>
        <el-table-column type="expand">
          <template slot-scope="props">
            <div class="giftTable">
              <!--赠品列表-->
              <el-table
                ref="giftTable"
                tooltip-effect="dark"
                :data="props.row.giftDetailList"
                width="100%"
              >
                <el-table-column
                  type="index"
                  width="60"
                  label="序号"
                  align="center"
                ></el-table-column>

                <el-table-column label="开始时间" align="center" width="270">
                  <template slot-scope="scope">
                    <el-time-picker
                      v-model="scope.row.buyBeginTime"
                      value-format="HH:mm:ss"
                      :disabled="disabledFlag"
                      placeholder="任意时间点"
                    ></el-time-picker>
                  </template>
                </el-table-column>

                <el-table-column label="结束时间" align="center" width="270">
                  <template slot-scope="scope">
                    <el-time-picker
                      v-model="scope.row.buyEndTime"
                      :disabled="disabledFlag"
                      @change="
                        selectchange(
                          scope.row,
                          scope.$index,
                          props.row,
                          props.$index
                        )
                      "
                      value-format="HH:mm:ss"
                      placeholder="任意时间点"
                    ></el-time-picker>
                  </template>
                </el-table-column>

                <el-table-column
                  label="操作"
                  align="center"
                  fixed="right"
                  v-if="!disabledFlag"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      @click="
                        deleteGiftsItem(
                          scope.row,
                          scope.$index,
                          props.row,
                          props.$index
                        )
                      "
                      type="text"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
      </el-form-item>

      <!--      <el-form-item label="门店范围：">-->
      <!--        <el-radio-group v-model="couponForm.isStore" :disabled="disabledFlag">-->
      <!--          <el-radio-button label="0">通用</el-radio-button>-->
      <!--          <el-radio-button label="1">指定门店</el-radio-button>-->
      <!--        </el-radio-group>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item-->
      <!--        label="适用门店："-->
      <!--        prop="couponShopList"-->
      <!--        v-if="couponForm.isStore == '1'"-->
      <!--      >-->
      <!--        <el-table-->
      <!--          :data="couponShopList"-->
      <!--          @selection-change="couponShopChecked"-->
      <!--          border-->
      <!--          v-if="couponForm.isStore == '1'"-->
      <!--          style="font-size: 10px;width:100%;"-->
      <!--          height="300"-->
      <!--          :header-cell-style="{background:'#eef1f6',color:'#606266'}"-->
      <!--        >-->
      <!--          <el-table-column type="selection" width="55" align="center"></el-table-column>-->
      <!--          &lt;!&ndash;<el-table-column prop="orgSeq" label="店铺编号" width="200" header-align="center"></el-table-column>&ndash;&gt;-->
      <!--          <el-table-column prop="storeName" label="店铺名称" width="180" header-align="center"></el-table-column>-->
      <!--          <el-table-column prop="storeOwnerName" label="店主姓名" width="100" header-align="center"></el-table-column>-->
      <!--          <el-table-column prop="storeType" label="店铺类型" width="100" header-align="center">-->
      <!--            <template slot-scope="scope">-->
      <!--              <span v-if="scope.row.storeType == 1">一代或二代店</span>-->
      <!--              <span v-if="scope.row.storeType == 2">三代店</span>-->
      <!--              <span v-if="scope.row.storeType == 3">四代店</span>-->
      <!--              <span v-if="scope.row.storeType == 4">体验店</span>-->
      <!--              <span v-if="scope.row.storeType == 5">专柜</span>-->

      <!--            </template>-->
      <!--          </el-table-column>-->
      <!--          <el-table-column prop="storeAddressDetail" label="店铺地址" header-align="center"></el-table-column>-->
      <!--        </el-table>-->
      <!--        <div style="margin-top:10px;">-->
      <!--          <el-button type="primary" @click="selectShop('couponForm')" v-if="!disabledFlag">选择门店</el-button>-->
      <!--          <el-button @click="deleteShop('couponForm')" v-if="!disabledFlag">删除门店</el-button>-->
      <!--        </div>-->
      <!--      </el-form-item>-->

      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm('couponForm')"
          v-if="!disabledFlag"
          >保 存</el-button
        >
        <el-button @click="resetForm('couponForm')">取 消</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="选择商品" :visible.sync="dialogVisibleGood" width="65%">
      <el-form
        :inline="true"
        :model="formInline"
        class="search-form-inline"
        style="margin-top:-20px;"
      >
        商品名称：
        <el-input
          v-model="formInline.goodsName"
          style="width:200px;"
          placeholder="商品名称"
        ></el-input>
        &nbsp;&nbsp; 商品分类：
        <el-select v-model="formInline.goodsType">
          <el-option value>全部</el-option>
          <el-option
            v-for="item in goodsTypeList"
            :key="item.goodsTypeId"
            :label="item.goodsTypeName"
            :value="item.goodsTypeId"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="getGoodsList(1)"
          >查询</el-button
        >
      </el-form>
      <el-table
        :data="goodsList"
        @selection-change="goodsChecked"
        border
        style="font-size: 10px;width:100%;"
        height="300"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="goodsName"
          label="商品名称"
          width="200"
          header-align="center"
        ></el-table-column>
        <el-table-column
          prop="goodsSeq"
          label="商品编码"
          width="180"
          header-align="center"
        ></el-table-column>
        <el-table-column
          prop="goodsTypeName"
          label="商品分类"
          width="180"
          header-align="center"
        ></el-table-column>
        <el-table-column
          prop="salePrice"
          label="商品价格"
          header-align="center"
          align="right"
        ></el-table-column>
        <el-table-column
          prop="unitName"
          label="销售单位"
          header-align="center"
        ></el-table-column>
      </el-table>
      <div class="block" style="margin-top:5px;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 30, 50, 100]"
          :current-page="listQuery.current"
          :page-size="listQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleGood = false">取 消</el-button>
        <el-button type="primary" @click="selectConfirm()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="选择门店" :visible.sync="dialogVisibleShop" width="65%">
      <el-form
        :inline="true"
        :model="formShop"
        class="search-form-inline"
        style="margin-top:-20px;"
      >
        大区：
        <el-select v-model="formShop.warzone">
          <el-option value>全部大区</el-option>
          <el-option
            v-for="item in warzoneList"
            :key="item.orgSeq"
            :label="item.orgName"
            :value="item.orgSeq"
          ></el-option>
        </el-select>
        <el-input
          v-model="formShop.shopName"
          style="width:200px;"
          placeholder="店铺名称"
        ></el-input>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="getShopList(1)"
          >查询</el-button
        >
      </el-form>
      <el-table
        ref="shopTable"
        :data="shopList"
        border
        style="font-size: 10px;width:100%;"
        height="300"
        @selection-change="shopChecked"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <!--<el-table-column prop="orgSeq" label="店铺编号" width="200" header-align="center"></el-table-column>-->
        <el-table-column
          prop="storeName"
          label="店铺名称"
          width="180"
          header-align="center"
        ></el-table-column>
        <el-table-column
          prop="storeOwnerName"
          label="店主姓名"
          width="100"
          header-align="center"
        ></el-table-column>
        <el-table-column
          prop="storeType"
          label="店铺类型"
          width="100"
          header-align="center"
        >
          <template slot-scope="scope">
            <template v-for="item in storeType">
              <span v-if="scope.row.storeType == item.value" :key="item.value">{{ item.label }}</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          prop="storeAddressDetail"
          label="店铺地址"
          header-align="center"
        ></el-table-column>
      </el-table>
      <div class="block" style="margin-top:5px;">
        <el-pagination
          @size-change="handleSizeChangeShop"
          @current-change="handleCurrentChangeShop"
          :page-sizes="[10, 20, 30, 50, 100]"
          :current-page="listQueryShop.current"
          :page-size="listQueryShop.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalShop"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleShop = false">取 消</el-button>
        <el-button type="primary" @click="shopConfirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  createCoupon,
  getWarzoneList,
  queryCouponById,
  queryStoreInfo,
  updateCoupon,
} from '@/api/promotionProgramEdit';
import { getmemberrule } from '@/api/membergrade';
import { getGoodsTypeList, querygoodsByName } from '@/api/product';
import imageUpload from '@/page/common/Image-upload';
import { dict } from '../../dict';

export default {
  components: {
    imageUpload,
  },
  data() {
    return {
      date_value4: '',
      loading: true,
      warzoneList: [],
      couponShopList: [],
      shopList: [],
      lsShopList: [],
      lsCouponShopList: [],
      goodsTypeList: [],
      useScopeList: [],
      goodsList: [],
      lsCouponGoodsList: [],
      lsGoodsList: [],
      checkList: [],
      memberLevelList: [],
      listone: [],
      couponForm: {
        mainPicList: [],
        detailPicList: [],
        giftMainPic: '', //卡券主图
        giftDetailPic: '', //卡券详情图
        uuid: '',
        couponSeq: '',
        couponName: '',
        discountType: '0',
        couponType: '3',
        validType: '2',
        validDate: '',
        validDateRange: '',
        validTimesList: null, //指定日期的数组
        validTimes: null, //指定日期
        goodsRangeTimes_copy: '',
        validCreateDate: '',
        validEndDate: '',
        dateRanged: '',
        beginDate: '',
        endDate: '',
        conponLimitMoney: 0,
        couponMoney: '',
        couponDiscount: '',
        useScope: '',
        isStore: '',
        comments: '',
        limitNum: '0',
        status: '',
        ifRangeDay: 0,
        couponPicture: '',
        memberDTOS: [],
        store: [],
        goods: [],
      },
      formInline: {
        goodsName: '',
        goodsType: '',
      },
      formShop: {
        shopName: '',
        warzone: '',
      },
      dialogVisibleGood: false,
      dialogVisibleShop: false,
      disabledFlag: false,
      listQuery: {
        current: 1,
        size: 10,
      },
      total: 0,
      listQueryShop: {
        current: 1,
        size: 10,
      },
      totalShop: 0,
      rules: {
        // couponName: [{ required: true, message: "请输入卡券名称", trigger: "blur" }]
        //   memberDTOS: [
        //     {required: false, message: "请选择目标会员", trigger: "blur"}
        //   ],
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '未来3天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 3);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '未来一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '未来一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            },
          },
        ],
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; //如果当天可选，就不用减8.64e7
        },
      },
    };
  },
  computed: {
    storeType: () => dict.storeType
  },
  mounted() {
    var v = this.$route.params.edit;
    this.disabledFlag = this.$route.params.disabledFlag;
    console.log('vwww', v);
    if (v) {
      // 修改，回显值
      this.couponForm.uuid = v.uuid;
      this.couponForm.couponSeq = v.couponSeq;
      this.couponForm.couponName = v.couponName;
      this.couponForm.validType = v.validType;
      this.couponForm.validDate = v.validDate;
      this.couponForm.validCreateDate = v.validCreateDate;
      this.couponForm.validEndDate = v.validEndDate;
      this.couponForm.conponLimitMoney = v.conponLimitMoney;
      this.couponForm.couponMoney = v.couponMoney;
      this.couponForm.couponDiscount = v.couponDiscount;
      this.couponForm.useScope = v.useScope;
      this.couponForm.isStore = v.isStore;
      this.couponForm.comments = v.comments;
      this.couponForm.status = v.status;
      this.couponForm.couponPicture = v.couponPicture;

      this.couponForm.limitNum = v.limitNum;
      this.couponForm.discountType = v.discountType;
      this.couponForm.beginDate = v.beginDate;
      this.couponForm.endDate = v.endDate;
      this.couponForm.validDateRange = [v.validCreateDate, v.validEndDate];
      this.couponForm.dateRanged = [v.beginDate, v.endDate];

      this.getCouponById(v.uuid);

      if (!this.disabledFlag && v.used == '1') {
        this.disabledFlag = true;
      }
    } else {
      // 新增，默认值
      this.couponForm.uuid = '';
      this.couponForm.validType = '2';
      this.couponForm.useScope = '0';
      this.couponForm.isStore = '0';
      this.couponForm.status = '1';
      this.couponForm.couponPicture = '3';
      this.couponForm.limitNum = '';
      this.getGoodsTypeList();
      this.getGoodsList(1);
      this.getShopList(1);
      this._getmemberinfo();
    }
    this.getWarzoneList();
  },
  methods: {
    goback() {
      this.$router.go('-1');
    },
    numberBlur(e, name) {
      if (e.target.value == '') {
        return;
      }
      let flag = new RegExp('^[0-9][0-9]*$').test(e.target.value);
      if (!flag) {
        this.$message({
          message: name + '请输入正整数',
          type: 'warning',
        });
        e.target.value = '';
      }
    },
    moneyBlur(e, name) {
      if (e.target.value == '') {
        return;
      }
      let flag = new RegExp(
        '(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)'
      ).test(e.target.value);
      if (!flag) {
        this.$message({
          message: name + '请输入正确金额',
          type: 'warning',
        });
        e.target.value = '';
      }
    },
    discountBlur(e, name) {
      if (e.target.value == '') {
        return;
      }
      let zz = new RegExp('^[0]+(.[0-9]{1,2})?$');
      if (
        !zz.test(e.target.value) ||
        e.target.value <= 0 ||
        e.target.value >= 1
      ) {
        this.$message({
          message: name + '请输入0-1以内的两位小数',
          type: 'warning',
        });
        e.target.value = '';
      }
    },
    _getmemberinfo() {
      let data = {
        size: 10,
        current: 1,
        condition: {},
        ascs: [],
        descs: [],
      };
      getmemberrule(data).then((res) => {
        this.memberLevelList = [];
        res.records.forEach((item, i) => {
          let data1 = {
            memberLevelName: item.gradelevelName,
            memberLevelId: item.uuid,
            isChecked: false,
          };
          this.memberLevelList.push(data1);
          if (
            this.couponForm.memberDTOS &&
            this.couponForm.memberDTOS.length != 0
          ) {
            this.couponForm.memberDTOS.forEach((dtoItem) => {
              this.memberLevelList.forEach((item) => {
                if (item.memberLevelId == dtoItem.memberLevelId) {
                  item.isChecked = true;
                }
              });
            });
            this.memberLevelList = JSON.parse(
              JSON.stringify(this.memberLevelList)
            );
          }
        });
      });
    },
    handleCheckedCitiesChange(v) {
      console.log(v, '8888');
      console.log(this.checkList, '999');
      console.log(this.memberLevelList, '000');
      console.log(this.couponForm.memberDTOS, '111');
    },
    getCouponById(uuid) {
      queryCouponById(uuid).then((res) => {
        if (
          res.result.memberGoodsInfoDTOS != null &&
          res.result.memberGoodsInfoDTOS.length > 0
        ) {
          this.useScopeList = res.result.memberGoodsInfoDTOS;
          this.useScopeList.forEach((item) => {
            if (item.ifRangeDay == 1) {
              item.goodsRangeTimes_copy = [
                item.goodsRangeTimes[0].beginTime,
                item.goodsRangeTimes[0].endTime,
              ];
            } else {
              item.goodsRangeTimes_copy = [];
            }
          });
        }

        if (
          res.result.userStoreInfoDTOS != null &&
          res.result.userStoreInfoDTOS.length > 0
        ) {
          this.couponShopList = res.result.userStoreInfoDTOS;
        }
        this.couponForm.memberDTOS = res.result.memberDTOS;

        this.couponForm.validTimesList = res.result.validTimes.map((item) => {
          return item.validBeginTime.split(' ')[0];
        });

        this.couponForm.mainPicList.push(res.result.giftMainPic);
        this.couponForm.detailPicList.push(res.result.giftDetailPic);

        this.getGoodsTypeList();
        this.getGoodsList(1);
        this.getShopList(1);
        this._getmemberinfo();
      });
      this.loading = false;
    },
    getWarzoneList() {
      let data = {};
      getWarzoneList(data).then((res) => {
        this.warzoneList = res.records;
      });
    },
    getGoodsTypeList() {
      getGoodsTypeList().then((res) => {
        this.goodsTypeList = res.records;
      });
      this.loading = false;
    },
    getGoodsList(current) {
      this.listQuery.current = current;
      let data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: {
          goodsName: this.formInline.goodsName,
          goodsTypeId: this.formInline.goodsType,
        },
        ascs: [],
        descs: [],
      };
      querygoodsByName(data).then((res) => {
        this.goodsList = res.records;
        this.total = res.total;
        // 去掉已选的
        for (var i in this.useScopeList) {
          this.removeByValue(
            this.goodsList,
            'uuid',
            this.useScopeList[i].goodsId
          );
          this.total -= 1;
          this.total = this.total < 0 ? 0 : this.total;
        }
      });
      this.loading = false;
    },
    getShopList(current) {
      this.listQueryShop.current = current;
      let data = {
        size: this.listQueryShop.size,
        current: this.listQueryShop.current,
        condition: {
          upOrgSeq: this.formShop.warzone,
          storeName: this.formShop.shopName,
        },
        ascs: [],
        descs: [],
      };
      /*
        if (this.planForm.uuid != null && this.planForm.uuid != "") {
          // 修改方案，调用查询卡券门店的接口
          queryStoreByPlanId(data).then(res => {
            this.shopList = res.records;
            this.total = res.total;
            // 设置回显
            this.checkboxInit();
          });
        } else {
        */
      // // 新增方案，调用仅查询门店的接口
      queryStoreInfo(data).then((res) => {
        this.shopList = res.records;
        this.totalShop = res.total;
        // 设置回显
        // this.checkboxInit();
        // 去掉已选的
        for (var i in this.couponShopList) {
          this.removeByValue(
            this.shopList,
            'uuid',
            this.couponShopList[i].uuid
          );
          this.totalShop -= 1;
          this.totalShop = this.totalShop < 0 ? 0 : this.totalShop;
        }
      });
      // }
      this.loading = false;
    },

    couponGoodsChecked(row) {
      this.lsCouponGoodsList = row;
    },
    goodsChecked(row) {
      this.lsGoodsList = row;
    },
    selectConfirm() {
      // 保存已选择的商品
      this.dialogVisibleGood = !this.dialogVisibleGood;

      this.lsGoodsList.forEach((item) => {
        item.goodsId = item.uuid;
      });

      this.useScopeList = this.useScopeList.concat(this.lsGoodsList);
      console.log('useScopeList123', this.useScopeList);

      for (var i in this.lsGoodsList) {
        this.removeByValue(this.goodsList, 'uuid', this.lsGoodsList[i].uuid);
      }
    },
    selectGoods() {
      // 显示选择商品对话框
      this.dialogVisibleGood = !this.dialogVisibleGood;
    },
    deleteGoods() {
      // 删除已选择的商品
      this.goodsList = this.goodsList.concat(this.lsCouponGoodsList);
      for (var i in this.lsCouponGoodsList) {
        this.removeByValue(
          this.useScopeList,
          'uuid',
          this.lsCouponGoodsList[i].uuid
        );
      }
    },

    addshijian(row, index) {
      console.log(row, index, 'oo');

      // this.useScopeList[index].giftDetailList.push({});
      let $table = this.$refs.giftTable;
      $table.toggleRowExpansion(row, true);
    },

    //选择目标会员
    changebox(v) {
      v.isChecked = !v.isChecked;
    },

    couponShopChecked(row) {
      this.lsCouponShopList = row;
    },
    shopChecked(row) {
      this.lsShopList = row;
    },
    shopConfirm() {
      // 保存已选择的门店
      this.dialogVisibleShop = !this.dialogVisibleShop;
      this.couponShopList = this.couponShopList.concat(this.lsShopList);
      for (var i in this.lsShopList) {
        this.removeByValue(this.shopList, 'uuid', this.lsShopList[i].uuid);
      }
    },
    selectShop() {
      // 显示选择门店对话框
      this.dialogVisibleShop = !this.dialogVisibleShop;
    },
    deleteShop() {
      // 删除已选择的门店
      this.shopList = this.shopList.concat(this.lsCouponShopList);
      for (var i in this.lsCouponShopList) {
        this.removeByValue(
          this.couponShopList,
          'uuid',
          this.lsCouponShopList[i].uuid
        );
      }
    },

    submitForm(formName) {
      if (
        this.couponForm.couponName == '' ||
        this.couponForm.couponName == null
      ) {
        this.$message.error('请输入卡券名称');
        return;
      }

      if (this.couponForm.discountType == '1') {
        if (
          this.couponForm.couponDiscount == '' ||
          this.couponForm.couponDiscount == null
        ) {
          this.$message.error('请输入卡券折扣');
          return;
        }
      } else {
        // if (this.couponForm.conponLimitMoney == '' || this.couponForm.conponLimitMoney == null) {
        //   this.$message.error('请输入卡券使用条件');
        //   return;
        // }
        if (
          this.couponForm.couponMoney == '' ||
          this.couponForm.couponMoney == null
        ) {
          this.$message.error('请输入卡券面值');
          return;
        }
        // if (parseInt(this.couponForm.conponLimitMoney) <= parseInt(this.couponForm.couponMoney)) {
        //   this.$message.error('卡券使用条件需大于卡券面值，请重新输入');
        //   return;
        // }
      }

      if (this.couponForm.mainPicList.length == 0) {
        this.$message.error('请上传购酒券主图');
        return;
      }

      if (this.couponForm.detailPicList.length == 0) {
        this.$message.error('请上传购酒券详情图');
        return;
      }

      if (this.useScopeList != null && this.useScopeList.length != 0) {
        this.useScopeList.forEach((item) => {
          if (item.ifRangeDay == 1 && item.goodsRangeTimes_copy != null) {
            let goodsRangeTimes = {
              beginTime: '',
              endTime: '',
            };
            item.goodsRangeTimes = goodsRangeTimes;
            item.goodsRangeTimes.beginTime = item.goodsRangeTimes_copy[0];
            item.goodsRangeTimes.endTime = item.goodsRangeTimes_copy[1];
          }
          if (item.ifRangeDay == 1 && item.goodsRangeTimes_copy == null) {
            this.$message.error('请设置指定日期');
            return;
          }
        });
      }
      console.log('useScopeList', this.useScopeList);

      // if (this.couponForm.dateRanged != null && this.couponForm.dateRanged.length == 2) {
      //   this.couponForm.beginDate = this.couponForm.dateRanged[0];
      //   this.couponForm.endDate = this.couponForm.dateRanged[1];
      // } else {
      //   this.$message.error('请选择活动日期');
      //   return;
      // }

      if (this.couponForm.validType == '1') {
        if (
          this.couponForm.validDate == '' ||
          this.couponForm.validDate == null
        ) {
          this.$message.error('请输入有效天数');
          return;
        }
      }
      if (this.couponForm.validType == '2') {
        if (
          this.couponForm.validDateRange != null &&
          this.couponForm.validDateRange.length == 2
        ) {
          this.couponForm.validCreateDate = this.couponForm.validDateRange[0];
          this.couponForm.validEndDate = this.couponForm.validDateRange[1];
        } else {
          this.$message.error('请选择生效日期');
          return;
        }
        if (this.couponForm.beginDate > this.couponForm.validCreateDate) {
          this.$message.error('生效日期不能早于活动日期');
          return;
        }
      }
      if (this.couponForm.useScope != '0' && this.couponForm.useScope != '1') {
        this.$message.error('请选择商品范围');
        return;
      }
      if (
        this.couponForm.useScope == '1' &&
        (this.useScopeList == null || this.useScopeList.length == 0)
      ) {
        this.$message.error('请选择商品');
        return;
      }
      if (this.couponForm.isStore != '0' && this.couponForm.isStore != '1') {
        this.$message.error('请选择门店范围');
        return;
      }
      if (
        this.couponForm.isStore == '1' &&
        (this.couponShopList == null || this.couponShopList.length == 0)
      ) {
        this.$message.error('请选择门店');
        return;
      }

      this.couponForm.memberDTOS = [];
      console.log('提交memberLevelList', this.memberLevelList);
      this.memberLevelList.forEach((item) => {
        if (item.isChecked) {
          this.couponForm.memberDTOS.push(item);
        }
      });
      // if (this.couponForm.memberDTOS == null || this.couponForm.memberDTOS.length == 0) {
      //   this.$message({showClose: true, message: "请选择目标会员", type: "info"});
      //   return;
      // }
      // else {
      //   this.rules.memberDTOS[0].required = false;
      // }
      // 去掉不需要的属性
      for (var i in this.couponShopList) {
        delete this.couponShopList[i].createTime;
        delete this.couponShopList[i].updateTime;
        delete this.couponShopList[i].agreement;
        delete this.couponShopList[i].baseCode;
        delete this.couponShopList[i].basePersonCode;
        delete this.couponShopList[i].buildingArea;
        delete this.couponShopList[i].businessDistrictType;
        delete this.couponShopList[i].businessLicense;
        delete this.couponShopList[i].city;
        delete this.couponShopList[i].companyName;
        delete this.couponShopList[i].createTime;
        delete this.couponShopList[i].createUser;
        delete this.couponShopList[i].distance;
        delete this.couponShopList[i].distanceStr;
        delete this.couponShopList[i].distanceUnit;
        delete this.couponShopList[i].doorwayPic;
        delete this.couponShopList[i].gradelevelId;
        delete this.couponShopList[i].leaseholdArea;
        delete this.couponShopList[i].legalPerson;
        delete this.couponShopList[i].legalPersonPhone;
        delete this.couponShopList[i].managerArea;
        delete this.couponShopList[i].openBeginTime;
        delete this.couponShopList[i].openDate;
        delete this.couponShopList[i].openEndTime;
        delete this.couponShopList[i].openStatus;
        delete this.couponShopList[i].openTime;
        delete this.couponShopList[i].openEnTime;
        delete this.couponShopList[i].practicalArea;
        delete this.couponShopList[i].province;
        delete this.couponShopList[i].status;
        delete this.couponShopList[i].storeAddress;
        delete this.couponShopList[i].storeAddressDetail;
        delete this.couponShopList[i].storeLat;
        delete this.couponShopList[i].storeLng;
        delete this.couponShopList[i].storeManagerName;
        delete this.couponShopList[i].storeManagerPhone;
        delete this.couponShopList[i].storeManagerPic;
        delete this.couponShopList[i].storeManagerTel;
        delete this.couponShopList[i].storeOwnerGrade;
        delete this.couponShopList[i].storeOwnerName;
        delete this.couponShopList[i].storeOwnerPhone;
        delete this.couponShopList[i].storeOwnerPic;
        delete this.couponShopList[i].upOrgSeq;
        delete this.couponShopList[i].upOrgZone;
        delete this.couponShopList[i].updateTime;
        delete this.couponShopList[i].updateUser;
        delete this.couponShopList[i].warehouseArea;
        delete this.couponShopList[i].wechatId;
        delete this.couponShopList[i].couponQuantity;
        delete this.couponShopList[i].couponQuantityOld;
        delete this.couponShopList[i].couponSumQuantity;
        delete this.couponShopList[i].couponSumQuantityOld;
      }
      console.log('useScopeList', this.useScopeList);
      for (var i in this.useScopeList) {
        delete this.useScopeList[i].createTime;
        delete this.useScopeList[i].updateTime;
        delete this.useScopeList[i].isCustomizeGoods;
        delete this.useScopeList[i].isMinUnit;
        delete this.useScopeList[i].kcAmount;
        delete this.useScopeList[i].minUnitGoodsId;
        delete this.useScopeList[i].paramValueList;
        delete this.useScopeList[i].pictures;
        delete this.useScopeList[i].salePrice;
        delete this.useScopeList[i].sysCode;
        delete this.useScopeList[i].tagType;
        delete this.useScopeList[i].unit;
        delete this.useScopeList[i].unitName;
      }
      this.couponForm.couponstore = this.couponShopList;
      this.couponForm.goods = this.useScopeList;

      if (
        this.couponForm.validTimesList &&
        this.couponForm.validTimesList.length != 0
      ) {
        this.couponForm.validTimes = this.couponForm.validTimesList.map(
          (item) => {
            return {
              validBeginTime: `${item} 00:00:00`,
              validEndTime: `${item} 23:59:59`,
            };
          }
        );
      }

      this.couponForm.giftDetailPic = this.couponForm.detailPicList[0];
      this.couponForm.giftMainPic = this.couponForm.mainPicList[0];

      console.log('this.couponForm');
      console.log(this.couponForm);

      this.$confirm('保存之前请确认所有配置信息是否正确', '提示', {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          if (this.couponForm.uuid == '') {
            // 新增卡券
            createCoupon(this.couponForm).then((res) => {
              if (res.code == '1') {
                this.$message({
                  showClose: true,
                  message: '保存成功',
                  type: 'success',
                });
                this.$router.push('couponList_gj');
              } else {
                this.$message.error('保存失败');
              }
            });
          } else {
            // 修改卡券
            updateCoupon(this.couponForm).then((res) => {
              if (res.code == '1') {
                this.$message({
                  showClose: true,
                  message: '保存成功',
                  type: 'success',
                });
                this.$router.push('couponList_gj');
              } else {
                this.$message({
                  showClose: true,
                  message: '保存失败',
                  type: 'success',
                });
              }
            });
          }
        })
        .catch(() => {});
    },
    resetForm(formName) {
      // this.$refs[formName].resetFields();
      this.$router.push('couponList_gj');
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.getGoodsList(1);
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.getGoodsList(val);
    },
    handleSizeChangeShop(val) {
      this.listQueryShop.size = val;
      this.getShopList(this.listQueryShop.current);
    },
    handleCurrentChangeShop(val) {
      this.listQueryShop.current = val;
      this.getShopList(val);
    },
    // 数组，属性，属性值
    removeByValue: function(arr, attr, value) {
      if (arr == null) {
        return;
      }
      var type = 0;
      var index = 0;
      for (var i in arr) {
        if (arr[i][attr] == value) {
          index = i;
          type = 1;
          break;
        }
      }
      if (type == 1) {
        arr.splice(index, 1);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-col-20 {
  border: 1px solid #ebeef5;
  margin-left: 150px;
  width: 60%;
}

.el-input {
  width: 60%;
}

.el-date-picker {
  width: 100%;
}

.search-form-inline {
  border: 1px solid #ebeef5;
  line-height: 30px;
  padding: 12px;
  margin-bottom: 5px;
}

.choose-date {
  display: flex;
  align-items: center;
}
</style>
